package com.franklin.ideaplugin.easytesting.core.rpc;

import com.franklin.ideaplugin.easytesting.common.log.ILogger;
import com.franklin.ideaplugin.easytesting.common.log.LoggerFactory;
import com.franklin.ideaplugin.easytesting.core.thread.EasyTestingThreadPool;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.*;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.Arrays;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author Ye Junhui
 * @since 2023/5/12
 */
public class NettyServer {

    private final int port;

    private EventLoopGroup bossGroup = new NioEventLoopGroup();
    private EventLoopGroup workerGroup = new NioEventLoopGroup();

    private static final ILogger log = LoggerFactory.getLogger(NettyServer.class);

    public NettyServer(int port) {
        this.port = port;
    }

    public boolean isEnable(){
        return this.port > 0;
    }

    public void start() {
        if (!isEnable()){
            return;
        }
        EasyTestingThreadPool.getServerThreadPool()
                .execute(() -> {
                    try {
                        // start server
                        ServerBootstrap bootstrap = new ServerBootstrap();
                        bootstrap.group(bossGroup, workerGroup)
                                .channel(NioServerSocketChannel.class)
                                .childHandler(new ChannelInitializer<SocketChannel>() {
                                    @Override
                                    public void initChannel(SocketChannel channel) throws Exception {
                                        channel.pipeline()
                                                .addLast(new IdleStateHandler(0, 0, 30 * 3, TimeUnit.SECONDS))  // beat 3N, close if idle
                                                .addLast(new HttpServerCodec())
                                                .addLast(new HttpObjectAggregator(5 * 1024 * 1024))  // merge request & reponse to FULL
                                                .addLast(new NettyHttpServerHandler(Arrays.asList(
                                                        new MethodInvokeRequestHandler(),
                                                        new HeartBeatRequestHandler()
                                                )));
                                    }
                                })
                                .childOption(ChannelOption.SO_KEEPALIVE, true);

                        // bind
                        ChannelFuture future = bootstrap.bind(port).sync();

                        log.info(">->->->->-> easy-testing remoting server start success, net-type = {}, port = {}", NettyServer.class, port);

                        // wait util stop
                        future.channel().closeFuture().sync();

                    } catch (InterruptedException e) {
                        log.info(">->->->->-> easy-testing remoting server stop.");
                    } catch (Exception e) {
                        log.error(">->->->->-> easy-testing remoting server error.", e);
                    } finally {
                        // stop
                        try {
                            workerGroup.shutdownGracefully();
                            bossGroup.shutdownGracefully();
                        } catch (Exception e) {
                            log.error(e.getMessage(), e);
                        }
                    }
                });
    }

    public void shutDown(){
        log.info("Easy-testing netty server stopping");
        if (Objects.nonNull(workerGroup)) {
            workerGroup.shutdownGracefully();
        }
        if (Objects.nonNull(bossGroup)){
            bossGroup.shutdownGracefully();
        }
    }
}
